1Writer Timestamp 2
### 対応パターン:
1. 行頭が箇条書き(- )
2. 行頭が未完了のチェックボックス(- [ ] )
3. 行頭が完了済みのチェックボックス(- [x] )
4. 行に既に hh:mm 形式の時刻が含まれている場合(@hh:mm を除く)
### 処理の説明:
- 行に既に hh:mm 形式の時刻が含まれている場合、その時刻の直後に -hh:mm 形式で現在時刻を追加。
- 行頭が箇条書きやチェックボックスの場合、その直後に現在時刻を hh:mm 形式で追加。
- 行頭に特定のパターンがない場合、行の先頭に現在時刻を追加。
- 最後に、元のカーソル位置を維持または適切に調整し、カーソルを再設定。
code:js
function addTimestampToSelectedLine() {
// Get the current time
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
// Format as hh:mm
const timestamp = ${hours}:${minutes};
// Get the selected range and line range
// Get the text of the selected line
const lineText = editor.getTextInRange(lineStart, lineEnd);
// Regular expression to match "hh:mm" format but not "@hh:mm"
const timeRegex = /(?<!@)(\d{2}:\d{2})/;
// Patterns for list items or checkboxes at the beginning of the line
const bulletRegex = /^(- \ \ |- \x\ |- )/; // Check if the line contains a time in "hh:mm" format (but not "@hh:mm")
const timeMatch = lineText.match(timeRegex);
if (timeMatch) {
// If a time is found, append "-hh:mm" after the matched time
const newLineText = lineText.replace(timeRegex, ${timeMatch[0]}-${timestamp});
editor.replaceTextInRange(lineStart, lineEnd, newLineText);
} else {
// If the line starts with a bullet or checkbox pattern
const bulletMatch = lineText.match(bulletRegex);
if (bulletMatch) {
// Insert the timestamp after the bullet or checkbox
const newLineText = ${bulletMatch[0]}${timestamp} ${lineText.slice(bulletMatch[0].length)};
editor.replaceTextInRange(lineStart, lineEnd, newLineText);
} else {
// If no bullet or checkbox, insert the timestamp at the beginning of the line
const newLineText = ${timestamp} ${lineText};
editor.replaceTextInRange(lineStart, lineEnd, newLineText);
}
}
// Restore the original cursor position by adjusting for the added/modified text
const newCursorPosition = originalStart + (timestamp.length + 1); // +1 for the space after the timestamp
editor.setSelectedRange(newCursorPosition, newCursorPosition);
}
// Execute the function to add the timestamp
addTimestampToSelectedLine();